﻿#region Copyright 2012 by Roger Knapp, Licensed under the Apache License, Version 2.0
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#endregion
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace CsProjectProjector
{
    class SolutionConverter
    {
        static readonly Regex csprojMatch = new Regex(@"Project\(""{[a-fA-F0-9-]{36}}""\)\s*=\s*""[^""]*"",\s*""(?<ProjFile>[^""]*\.csproj)"",\s*""(?<ProjGuid>{[a-fA-F0-9-]{36}})""");
        static readonly Regex vstudioVersMatch = new Regex(@"(?<=^Microsoft Visual Studio Solution File, Format Version\s+)[\d\.]{5}", RegexOptions.Multiline);
        static readonly Regex vstudioNameMatch = new Regex(@"(?<=^# Visual Studio\s+)\d{4}", RegexOptions.Multiline);
        private readonly string _slnpath;

        public SolutionConverter(string slnpath)
        {
            _slnpath = slnpath;
        }

        public void ConvertSolution(string[] templates)
        {
            string root = Path.GetDirectoryName(_slnpath);
            string slnText = File.ReadAllText(_slnpath);

            foreach (string template in templates)
            {
                string newSln = Path.ChangeExtension(_slnpath, Path.GetFileNameWithoutExtension(template) + ".sln");
                string newSlnText =
                    csprojMatch.Replace(
                        slnText,
                        m => m.Value.Replace(
                            m.Groups["ProjFile"].Value,
                            Path.ChangeExtension(m.Groups["ProjFile"].Value, "." + Path.GetFileName(template))
                        )
                    );

                string newExtension = "." + Path.GetFileName(template);
                int? toolset = null;

                foreach (string projpath in csprojMatch.Matches(slnText)
                    .OfType<Match>()
                    .Select(m => Path.Combine(root, m.Groups["ProjFile"].Value))
                    .Where(File.Exists))
                {
                    var proj = new ProjectConverter(projpath);
                    proj.ConvertProject(XElement.Load(template), template);
                    proj.MapProjectReferences(newExtension);
                    proj.Save(Path.ChangeExtension(projpath, newExtension));
                    toolset = Math.Min(proj.ToolsVersion, toolset.GetValueOrDefault(proj.ToolsVersion));
                }

                if (toolset == 35)
                {
                    newSlnText = vstudioVersMatch.Replace(newSlnText, "10.00");
                    newSlnText = vstudioNameMatch.Replace(newSlnText, "2008");
                }
                else if (toolset == 40)
                {
                    newSlnText = vstudioVersMatch.Replace(newSlnText, "11.00");
                    newSlnText = vstudioNameMatch.Replace(newSlnText, "2010");
                }
                else
                    throw new ArgumentOutOfRangeException("Unable to determine the solution toolset.");

                File.WriteAllText(newSln, newSlnText);
            }
        }
    }
}
